package com.online.music.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.online.music.entity.dto.LikePageDTO;
import com.online.music.entity.po.Like;
import com.online.music.entity.po.Playlist;
import com.online.music.mapper.LikeMapper;
import com.online.music.mapper.SongMapper;
import com.online.music.service.ILikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.online.music.utils.UserContextUtil;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;

import java.util.List;

import com.online.music.common.Result;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: Leno
 * @Date: 2025-01-31
 * @Description: LikeServiceImpl
 */
@Service
@RequiredArgsConstructor
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements ILikeService {

    private final LikeMapper likeMapper;

    @Override
    public Result<Page<Playlist>> findPage(Integer pageNum, Integer pageSize, LikePageDTO like) {
        Page<Like> page = new Page<>(pageNum, pageSize);

        QueryWrapper<Like> qw = new QueryWrapper<>();
        qw.eq("l.user_id", UserContextUtil.getUserId());
        if (StrUtil.isNotBlank(like.getSongName())) {
            qw.eq("s.name", like.getSongName());
        }
        Page<Playlist> result = likeMapper.findPage(page, qw);

        return Result.success(result);
    }

    @Override
    @Transactional
    public Result<String> deleteBatch(List<Long> playlistIds) {
        // 删除前先判断是否存在...
        lambdaUpdate()
                .in(Like::getPlaylistId, playlistIds)
                .eq(Like::getUserId, UserContextUtil.getUserId())
                .remove();
        return Result.successMsg("删除成功");
    }

    @Override
    public Result<Boolean> like(Like like) {
        // 点赞功能
        Like one = lambdaQuery()
                .eq(Like::getPlaylistId, like.getPlaylistId())
                .eq(Like::getUserId, UserContextUtil.getUserId())
                .one();
        if (one == null) {
            like.setUserId(UserContextUtil.getUserId());
            likeMapper.insert(like);
        }
        return Result.success(true);
    }

}

